<?php
namespace app\oa\controller;
use \app\oa\controller\Role as RoleController;
use app\oa\ext\Core;
use app\oa\ext\Role;
use app\oa\ext\UserStatus;
use app\oa\model\Task;
use think\Config;
use think\Request;
vendor('wechat/autoload');
use EasyWeChat\Foundation\Application;

/**
 * 主管
 * Class Supervisor
 * @package app\oa\controller
 */
class Supervisor extends RoleController {
    protected function getRole()
    {
        return [Role::Supervisor, Role::DeputySupervisor];
    }

    public function index() {
        $tasks = Task::all(['status'=>2, 'department_id'=>UserStatus::getDepartmentID()]);
        $this->assign("tasks", $tasks);

        $sendTasks = Task::all(['status'=>8, 'department_id'=>UserStatus::getDepartmentID()]);
        $this->assign("sendTasks", $sendTasks);
        return $this->fetch("supervisor/index");
    }

    public function verify($id, $pass = 1) {
        $task = Task::get($id);
        if($pass) {
            $task['status'] = 3;
        }else {
            $task['status'] = 10;
        }

        if($task->save()) {
            $this->success("操作成功");
        }
    }


    public function alterTask(Request $request, $id) {
        $core = new Core();
        $core->checkDepartment($id);
        $core->checkStatus($id, 2);
        $core->upload($request, $id);
    }

    public function sendTask($id) {
        $core = new Core();
        $core->checkDepartment($id);
        $core->checkStatus($id, 8);
        // 获取任务信息
        $task = Task::get($id);
        $name = $task['name'];
        $files = $task['files'];
        $url = $files[count($files) - 1]['url'];
        // 发送公众号信息
        $app = $this->initApp();
        $app->broadcast->sendText("<a href='{$url}'>{$name}</a>");

        $this->success("操作成功");
    }
    private function initApp() {
        $mp = get_bind_mp();
        if(!$mp) {
            $this->error('错误');
        }
        $options = array_merge(
            Config::get('mp_options'),
            [
                'app_id'=> $mp['appid'],
                'secret'=> $mp['appsecret'],
                'token' => $mp['token'],
            ]
        );
        return new Application($options);
    }
}